package com.yupi.picturebackend.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.yupi.picturebackend.exception.BusinessException;
import com.yupi.picturebackend.exception.ErrorCode;
import com.yupi.picturebackend.exception.ThrowUtils;
import com.yupi.picturebackend.manager.sharding.DynamicShardingManager;
import com.yupi.picturebackend.model.dto.space.SpaceAddRequest;
import com.yupi.picturebackend.model.dto.space.SpaceQueryRequest;
import com.yupi.picturebackend.model.entity.Space;
import com.yupi.picturebackend.model.entity.SpaceUser;
import com.yupi.picturebackend.model.entity.User;
import com.yupi.picturebackend.model.enums.SpaceLevelEnum;
import com.yupi.picturebackend.model.enums.SpaceRoleEnum;
import com.yupi.picturebackend.model.enums.SpaceTypeEnum;
import com.yupi.picturebackend.model.vo.SpaceVO;
import com.yupi.picturebackend.model.vo.UserVO;
import com.yupi.picturebackend.service.SpaceService;
import com.yupi.picturebackend.mapper.SpaceMapper;
import com.yupi.picturebackend.service.SpaceUserService;
import com.yupi.picturebackend.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
* @author 伍立权
* @description 针对表【space(空间)】的数据库操作Service实现
* @createDate 2025-03-27 21:25:24
*/
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
    implements SpaceService{

    @Resource
    private UserService userService;
    //编程式事务
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private SpaceUserService spaceUserService;
//    @Resource
//    @Lazy
//    private DynamicShardingManager dynamicShardingManager;


    /**
     * 判断空间是否可用
     * @param space
     * @param add
     */
    @Override
    public void validSpace(Space space, boolean add) {
        //参数校验
        ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);
        //从对象中获取值
        String spaceName = space.getSpaceName();//空间名字
        Integer spaceLevel = space.getSpaceLevel();//空间等级值
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);//空间等级枚举对象
        Integer spaceType = space.getSpaceType();//空间类型
        SpaceTypeEnum enumByValue = SpaceTypeEnum.getEnumByValue(spaceType);
        //判断是否是创建
        if (add){
            if (StrUtil.isBlank(spaceName)){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"空间名称不能为空");
            }
            if (spaceLevel == null){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"空间等级不能为空");
            }
            if (spaceType == null){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"空间类型不能为空");
            }
        }
        //要修改数据时，如要该空间等级
        if (spaceLevel != null && spaceLevelEnum == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"该空间等级不存在");
        }
        //判断空间名称长度
        if (StrUtil.isNotBlank(spaceName) && spaceName.length() >= 30){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"空间名称过长");
        }
        //判断空间类型是否存在
        if (enumByValue == null && spaceType != null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"空间类型不存在");
        }
    }

    /**
     * 自动填充限额数据
     * @param space
     */
    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        //参数校验
        ThrowUtils.throwIf(space == null,ErrorCode.PARAMS_ERROR);
        //获取该空间的等级
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        //填充限额数据
        if (spaceLevelEnum != null){
            //根据空间等级获取最大容量和数量
            long maxCount = spaceLevelEnum.getMaxCount();
            long maxSize = spaceLevelEnum.getMaxSize();
            //这些数据为空，才插入
            if (space.getMaxCount() == null){
                space.setMaxCount(maxCount);
            }
            if (space.getMaxSize() == null){
                space.setMaxSize(maxSize);
            }
        }
    }

    /**
     * 新建空间
     * @param spaceAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
        //参数校验
        ThrowUtils.throwIf(loginUser == null,ErrorCode.NOT_LOGIN_ERROR);
        //设置空间参数
        Space space = new Space();
        BeanUtils.copyProperties(spaceAddRequest,space);
        //如果名字、等级、类型为空，设置默认值
        if (StrUtil.isBlank(space.getSpaceName())){
            space.setSpaceName("默认空间");
        }
        if (space.getSpaceLevel() == null){
            space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        if (space.getSpaceType() == null){
            space.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
        }
        //填充容量和大小
        fillSpaceBySpaceLevel(space);
        //校验空间是否可用
        validSpace(space,true);
        //其它参数设置
        space.setUserId(loginUser.getId());
        //当用户创建的不是普通版，且非管理员
        if (space.getSpaceLevel() != SpaceLevelEnum.COMMON.getValue() && !userService.isAdmin(loginUser)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"无权限创建指定级别的空间");
        }
        //控制同一个用户只能创建一个私有空间、以及一个团队空间，操作数据库
        //根据登录用户的id获取特定的锁
        String lock = String.valueOf(loginUser.getId()).intern();
        synchronized (lock){//本地锁
            Long newSpaceId = transactionTemplate.execute(status -> {
                //判断是否已有空间
                LambdaQueryWrapper<Space> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Space::getUserId, loginUser.getId())
                        .eq(Space::getSpaceType,space.getSpaceType());
                List<Space> list = this.list(queryWrapper);
                ThrowUtils.throwIf(!list.isEmpty(), ErrorCode.OPERATION_ERROR, "每个用户每类空间只能创建一个");
                //创建
                boolean save = this.save(space);
                ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR, "向数据库中添加空间失败");
                //创建成功后，如果是团队空间，将该用户添加进去，为管理员
                if (SpaceTypeEnum.TEAM.getValue() == spaceAddRequest.getSpaceType()){
                    SpaceUser spaceUser = new SpaceUser();
                    spaceUser.setSpaceId(space.getId());
                    spaceUser.setUserId(loginUser.getId());
                    spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                    boolean result = spaceUserService.save(spaceUser);
                    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建团队成员记录失败");
                }
                // 创建分表（仅对团队空间生效）
//                dynamicShardingManager.createSpacePictureTable(space);
                return space.getId();
            });
            return Optional.ofNullable(newSpaceId).orElse(-1L);
        }
    }

    /**
     * 根据空间对象获取封装对象
     * @param space
     * @param request
     * @return
     */
    @Override
    public SpaceVO getSpaceVo(Space space, HttpServletRequest request) {
        //对象转换
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        //关联用户信息
        Long userId = space.getUserId();
        if (userId != null && userId > 0){
            User loginUser = userService.getLoginUser(request);
            UserVO userVO = userService.getUserVO(loginUser);
            spaceVO.setUser(userVO);
        }
        return spaceVO;
    }

    /**
     * 构造空间的条件查询器
     * @param spaceQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
        if (spaceQueryRequest == null){
            return queryWrapper;
        }
        //从对象中获取值
        Long id = spaceQueryRequest.getId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        Integer spaceType = spaceQueryRequest.getSpaceType();
        Long userId = spaceQueryRequest.getUserId();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();
        //添加查询条件
        queryWrapper.eq(ObjUtil.isNotEmpty(id),"id",id);
        queryWrapper.like(StrUtil.isNotBlank(spaceName),"spaceName",spaceName);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceLevel),"spaceLevel",spaceLevel);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceType),"spaceType",spaceType);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId),"userId",userId);
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 分页获取空间列表
     * @param spacePage
     * @param request
     * @return
     */
    @Override
    public Page<SpaceVO> getSpaceVoPage(Page<Space> spacePage, HttpServletRequest request) {
        //1.参数校验
        List<Space> spaceList = spacePage.getRecords();
        Page<SpaceVO> page = new Page<>(spacePage.getCurrent(),spacePage.getSize(),spacePage.getTotal());
        //如果分页结果为空，直接返回
        if (spaceList == null){
            return page;
        }
        //2.将Space集合转为Vo集合
        List<SpaceVO> spaceVOList = new ArrayList<>();
        for (Space space : spaceList) {
            SpaceVO spaceVO = SpaceVO.objToVo(space);
            User user = userService.getById(space.getUserId());
            spaceVO.setUser(userService.getUserVO(user));
            spaceVOList.add(spaceVO);
        }
        page.setRecords(spaceVOList);
        return page;
    }

    /**
     * 校验空间权限
     * @param space
     * @param loginUser
     */
    @Override
    public void checkSpaceAuth(Space space, User loginUser) {
        if (!space.getUserId().equals(loginUser.getId())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
    }
}




